var resourcesJs = function(targetObj){
	this.targetObj = targetObj;
	this.sysUtils = new kendoUtils();
	this.resourcesNodeInfo = null;
	this.init();
	return this;
};
resourcesJs.prototype={
		init:function(){
			var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find(".search-panel"));
			var bindFunctionArray = [{fName:"queryInfo",fs:this.findGridData},{fName:"resetInfo",fs:this.resetInfo}];
			this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
			this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
			this.treeView();
			this.createGrid();
		},
		treeView:function(){
			var that = this;
			JsonpAjax(baseApiPath + "basSystemResource/resourcesTree",null,function(result){
				if(result.constructor == Object){
					that.targetObj.find("#resourcesTreeView").kendoTreeView({
						dataTextField:"fullName",
						dataSource:[result.data],
						schema: {
							model: {
								hasChildren: "hasChildren",
								id: "id",
								children: "items",
								expanded:"expanded"
							}
						},select:function(e){
							var dataItem = this.dataItem(e.node);
							that.resourcesNodeInfo=dataItem;//保存选中树节点信息
							that.findGridData();
						},
						dataBound:function(e){
							//默认选中根节点
							if (that.resourcesNodeInfo == null){
								var treeview = that.targetObj.find("#resourcesTreeView").data("kendoTreeView");
								var nodes = treeview.dataSource.view();
								var nodeElement = treeview.findByText(nodes[0].fullName);
								treeview.select(nodeElement);
								that.resourcesNodeInfo=nodes[0];//保存选中树节点信息
								that.findGridData();
							}
						}
					});
				}
			},"GET","json",null);
		},
		/*
		 * 增加节点
		 */
		addNode:function(obj){
			var treeview = this.targetObj.find("#resourcesTreeView").data("kendoTreeView");
			treeview.append(obj,treeview.select());

		},
		/*
		 * 去掉节点
		 */
		minusNode:function(ids){
			var treeview = this.targetObj.find("#resourcesTreeView").data("kendoTreeView");
			var nodeArray = new Array();
			this.judgeChildNodes(ids,treeview.dataSource.view(),nodeArray);
			for(var i = 0;i<nodeArray.length;i++){
				treeview.remove(treeview.findByText(nodeArray[i].fullName));	
			}
		},
		/*
		 * 判断 树是否有 子节点
		 */
		judgeChildNodes:function(ids,nodes,checkedNodes){
			for (var i = 0; i < nodes.length; i++) {
				var strArr = ids.toString().split(",");
				for (var j=0;j<strArr.length;j++){
					if ($.trim(nodes[i].id) == $.trim(strArr[j])){
						checkedNodes.push(nodes[i]);
					}
				}
				if (nodes[i].hasChildren) {
					resourcesInfoJs.judgeChildNodes(ids,nodes[i].children.view(), checkedNodes);
				}
			}
		},
		findGridData:function(e){
			var that = this;
			if(isNotEmpt(e)){
				that = $(e.target).data("that");
			}
			var jsonObj = that.sysUtils.getBindDocJson();

			if(that.resourcesNodeInfo["dataType"] == "SYSTEM"){   //选择系统层
				jsonObj["systemManageId"] = that.resourcesNodeInfo["id"];
				jsonObj["resourceType"] = parseInt(Utils.getModelValueByModelKey(BASIS.RESOURCE_TYPE.RESOURCE_TYPE_MODULE,Utils.systemType.SYS));//模块
			}else if(that.resourcesNodeInfo["dataType"] != "-1"){  //选择资源层
				jsonObj["parentCode"] = that.resourcesNodeInfo["dataCode"];
			}
			console.info(jsonObj);
			var urls = baseApiPath + "basSystemResource/resourcesList";
			var kendoGrid  = that.targetObj.find("#resourcesList").data("kendoGrid");
			var dataT = {optype:"find",json:JSON.stringify(jsonObj),curdatetime:new Date().getTime()};
			var dataSource = that.sysUtils.getDataSource({url:urls,data:dataT,dataType:"json",cccurdatetime:new Date().getTime()});
			kendoGrid.setDataSource(dataSource); 
		},
		/*
		 * 创建空列表
		 */
		createGrid:function(){
			var that = this;
			var columns = this.gridColumns();
			var dataTran = {optype:"query"} ;
			this.sysUtils.createGird(this.targetObj.find("#resourcesList"), {
				dataSource:[],
				selectable: "single",
				autoSync: true,
				reorderable: true,
				columnMenu: true,
				pageable: {input: true,numeric: false},
				columns: columns,
				dataBound:function(){
					that.targetObj.find("#resourcesList").find("tr:gt(0)").unbind("dblclick");
					that.targetObj.find("#resourcesList").find("tr:gt(0)").dblclick(function(e){
						var grid = that.targetObj.find("#resourcesList").data("kendoGrid");
						var dataItem = grid.dataItem(grid.select());
						//打开查看窗口
						that.openResourcesWindow(dataItem["id"]);
					});	
				}
			});
		},
		/*
		 * 加载list 列表
		 */
		gridColumns:function(){
			var userType=user.userType;
			var  items=[
			            {
			            	width:30,
			            	headerTemplate: '<input type="checkbox" gridId="resourcesList" onclick="gridCheckAll(this)" />',
			            	template: '<input name="resourcesCheck" type="checkbox" value="${id}"/>'
			            },
			            {
			            	title: "资源名称",
			            	field: "resourceName",
			            	filterable: false
			            },
			            {
			            	title: "资源编码",
			            	field: "resourceCode"
			            },
			            {
			            	title: "资源类型",
			            	template:"#:Utils.getModelNameByParentKey(BASIS.RESOURCE_TYPE.ROOT,resourceType,Utils.systemType.SYS)#"
			            },
			            {
			            	title: "状态",
			            	template:"#:Utils.getModelNameByParentKey(BASIS.DATA_STATUS.ROOT,status,Utils.systemType.SYS)#"
			            }
			            ];
			return items;
		},
		resetInfo:function(e){
			var that = $(e.target).data("that");
			that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
		},
		//弹出窗口
		openResourcesWindow:function(resourceId,isEdit){
			var that = this;
			if(that.resourcesNodeInfo.dataType=="-1"){
				notification({ title:"提示信息",message:"根节点下不能做新增和编辑操作!!"},'info');
				return ;
			}
			var titles = "";
			that.editResult = null;
			that.isEdit = null;
			var MODULE = Utils.getModelValueByModelKey(BASIS.RESOURCE_TYPE.RESOURCE_TYPE_MODULE,Utils.systemType.SYS);//模块
			var MENU = Utils.getModelValueByModelKey(BASIS.RESOURCE_TYPE.RESOURCE_TYPE_MENU,Utils.systemType.SYS);    //菜单
			//默认选择模块
			that.selectType = MODULE;
			//判断默认选择项
			if(that.resourcesNodeInfo["dataType"] == that.selectType){   //选择模块资源
				that.selectType = MENU;
			}else if(that.resourcesNodeInfo["dataType"] == MENU){  //选择菜单
				that.selectType = Utils.getModelValueByModelKey(BASIS.RESOURCE_TYPE.RESOURCE_TYPE_FUNCTION,Utils.systemType.SYS); //按钮
			}
			var openwidonw = function(){
				that.resourcesDivId = that.sysUtils.openWindow(that.resourcesDivId,{
					title:titles,
					height:"365px",
					width:"620px",
					resizable:false,
					content:"views/framework/resources/edit.html"
				}, true);
			};

			var ajaxPost = function(){
				JsonpAjax(baseApiPath+"resources/queryResourceInfo?resourceId=" + resourceId,null,"json",function(result){
					that.editResult = result;
					openwidonw();
				}); 
			};
			if(undefined == resourceId && null == isEdit){  //表示新增界面
				titles = "新增资源信息";
				that.isEdit = false;
				openwidonw();
			}else if(true == isEdit){  //编辑界面
				//获取选中行的用户编号
				var grid = this.targetObj.find("#resourcesList").data("kendoGrid");
				var dataItem = grid.dataItem(grid.select());
				if(null == dataItem){
					notification({ title:"操作失败",message:"请选择至少一条需要修改的记录!!"},'info');
					return;
				}
				resourceId = dataItem["id"];
				titles = "编辑资源信息";
				that.isEdit = true;
				ajaxPost();
			}else{    //查询界面
				titles = "查询资源信息";
				that.isEdit = false;
				ajaxPost();
			}
		},
		deleteResource:function(){
			var that = this;
			//获取被选中的选择框
			var resourceIdList = "";
			var ids = new Array();
			that.targetObj.find("input[name='resourcesCheck']:checked").each(function(){
				resourceIdList += $(this).val() +",";
				ids.push($(this).val());
			});
			if("" == resourceIdList){
				notification({ title:"操作失败",message:"请选择至少一条需要删除的记录!!"},'info');
				return;
			}
			notification({ title:"确认信息",message:"确定需要删除选中的资源信息？"},'confirm',{callback:function(){
				resourceIdList = resourceIdList.substring(0, resourceIdList.length - 1);
				JsonpAjax(baseApiPath+"resources/deleteResource",resourceIdList,"json",function(result){
					that.findGridData();
					that.minusNode(ids);
				});
			}});
		},
		/**
		 * 修改资源状态
		 */
		updateResourceStatus:function(statusCode){
			var that = this;
			var statusName = null;
			if("Start" == statusCode){
				statusName = "启用";
			}else if("Stop" == statusCode){
				statusName = "停用";
			}else{
				notification({ title:"操作失败",message:"状态码异常，请重试!!"},'info');
				return;
			}
			//获取呗选中的选择框
			var valStr = "";
			this.targetObj.find("input[name='resourcesCheck']:checked").each(function(){
				valStr += "'" + $(this).val() +"',";
			});
			if("" == valStr){
				notification({ title:"操作失败",message:"请勾选至少一条需要"+statusName+"的记录!!"},'info');
				return;
			}
			notification({ title:"确认信息",message:"确定需要"+statusName+"选中的资源信息？"},'confirm',{callback:function(){
				valStr = valStr.substring(0, valStr.length - 1);
				JsonpAjax(baseApiPath+"resources/updateStatus?id="+valStr+"&statusCode="+statusCode,"","json",function(result){
					that.findGridData();
				});
			}});
		},
		/**
		 * 更新节点名称
		 * @param nodeId
		 * @param fullName
		 */
		updateNode:function(nodeId,fullName){
			var treeview = this.targetObj.find("#resourcesTreeView").data("kendoTreeView");
			var selectItems = treeview.dataItem(treeview.select()).items;
			for(var i = 0; i<selectItems.length;i++){
				if(selectItems[i]["id"] == nodeId){
					var li = this.targetObj.find("li[data-uid='"+selectItems[i]["uid"]+"']");
					var span = li.find(".k-in:first");
					var img = span.find("img");
					span.empty().append(img).append(fullName);
				}
			}
		}
};

var resourcesEditJs = function(targetObj){
	this.targetObj = targetObj;
	this.sysUtils = new kendoUtils();
	this.btnMaps = null;
	this.init();
	return this;
};

resourcesEditJs.prototype={
		init:function(){
			var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
			var bindFunctionArray = [{fName:"saveInfo",fs:this.saveInfo},{fName:"cancelSave",fs:function(){$("#"+resourcesInfoJs.resourcesDivId).data("kendoWindow").close();}}];
			this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
			this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
			var statusDiv = this.targetObj.find("input[data-bind='value:status']");
			var resourceType = this.targetObj.find("input[data-bind='value:resourceType']");
			var statusStart = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_START,Utils.systemType.SYS);
			Utils.createDataDictDropDownList([{div:statusDiv,parentModelKey:BASIS.DATA_STATUS.ROOT,select:statusStart},
			                                  {div:resourceType,parentModelKey:BASIS.RESOURCE_TYPE.ROOT,select:resourcesInfoJs.selectType}],this,this.loadData,Utils.systemType.SYS);
		},
		//检查是否需要加载展示数据
		loadData:function(){
			this.targetObj.find("input[data-bind='value:resourceType']").data("kendoDropDownList").enable(false);
			var RSFun = Utils.getModelValueByModelKey(BASIS.RESOURCE_TYPE.RESOURCE_TYPE_FUNCTION,Utils.systemType.SYS);    //按钮
			this.btnMaps = this.btnMapFull();
			var dropDownList = null;
			if(RSFun == resourcesInfoJs.selectType){  //添加功能按钮
				var that = this;
				var btnType = this.targetObj.find("#btnType");
				btnType.parent("div").css("display","block");
				dropDownList = btnType.kendoDropDownList({
					dataTextField: "name",
					dataValueField: "code",
					dataSource: this.btnMaps.values(),
					change:function(e){
						var value = this.value();
						var btnObj = that.btnMaps.get(value);
						if(null == btnObj) return;
						that.targetObj.find("#resourceImg").attr("src",btnObj["imgPth"]);
					}
				}).data("kendoDropDownList");
				this.targetObj.find("div.upload-case").find("a").remove(); 
			}
			if(null == resourcesInfoJs.editResult) return; //新增啥都不需要做
			//加载数据
			this.sysUtils.setBindFieldValue(resourcesInfoJs.editResult);
			if(RSFun == resourcesInfoJs.selectType){		//添加功能按钮
				var code = this.getBtnCode(resourcesInfoJs.editResult["imgUrl"]);
				this.sysUtils.setBindFieldValue({"btnType":code});
			}
			if(isNotEmpt(resourcesInfoJs.editResult["imgUrl"])){  //如果有存在图片，则显示在右边
				this.targetObj.find("#resourceImg").attr("src",resourcesInfoJs.editResult["imgUrl"]);
			}
			if(resourcesInfoJs.isEdit == false){  //表示查看
				//查看需要屏蔽一些字段
				var that = this;
				this.targetObj.find("div.upload-case").find("a").remove(); 
				this.targetObj.find(".basicInfo-btn").remove();
				this.targetObj.find("input").attr("disabled","disabled");
				this.targetObj.find("textarea").attr("disabled","disabled");
				this.targetObj.find("input[data-bind='value:status']").data("kendoDropDownList").enable(false);
				if(RSFun == resourcesInfoJs.selectType){  //添加功能按钮
					this.targetObj.find("#btnType").data("kendoDropDownList").enable(false);
				}
			}
		},
		saveInfo:function(e){
			var that =  $(e.target).data("that");
			if(validityForm(that.targetObj)){
				var resourcesInfoJson = that.sysUtils.getBindDocJson();
				if(resourcesInfoJs.resourcesNodeInfo["dataType"] =="SYSTEM"){
					resourcesInfoJson["systemManageId"] = resourcesInfoJs.resourcesNodeInfo["id"];
					resourcesInfoJson.parentCode="SYS";
				}else{ //如果为资源，直接取上级节点所属系统ID
					resourcesInfoJson["systemManageId"] = resourcesInfoJs.resourcesNodeInfo["model"]["systemManageId"];
					resourcesInfoJson.parentCode=resourcesInfoJs.resourcesNodeInfo.dataCode;
				}
				resourcesInfoJson["imgUrl"] = that.targetObj.find("#resourceImg").attr("src");
				if(resourcesInfoJson["imgUrl"].indexOf("default") > 0 ){
					resourcesInfoJson["imgUrl"] = "";
				}
				if(resourcesInfoJs.isEdit){
					resourcesInfoJson.createBy=resourcesInfoJs.editResult.createBy;
					resourcesInfoJson.createTime=resourcesInfoJs.editResult.createTime;
					resourcesInfoJson.id=resourcesInfoJs.editResult.id;
					resourcesInfoJson.resourceSort=resourcesInfoJs.editResult.resourceSort;
					resourcesInfoJson.resourceCode=resourcesInfoJs.editResult.resourceCode;
				}
				JsonpAjax(baseApiPath+"resources/saveResources?isEdit=" + resourcesInfoJs.isEdit,JSON.stringify(resourcesInfoJson),"json",function(result){
					if(result.constructor == Object){
						resourcesInfoJs.findGridData();
						var RSFun = Utils.getModelValueByModelKey(BASIS.RESOURCE_TYPE.RESOURCE_TYPE_FUNCTION,Utils.systemType.SYS);    //按钮
						if(RSFun != resourcesInfoJs.selectType){
							if(!resourcesInfoJs.isEdit){
								var nodeObj = {model:result,hasChildren:false,downChecked:true,id:result.id,fullName:result.resourceName,dataCode:result.resourceCode,dataType:result.resourceType};
								resourcesInfoJs.addNode(nodeObj);  //增加节点
							}else{  //修改节点名称
								resourcesInfoJs.updateNode(result.id,result.resourceName);
							}
						}
					}
					$("#"+resourcesInfoJs.resourcesDivId).data("kendoWindow").close();
				}); 
			}
		},
		/**
		 * 组建按钮功能信息，按钮对应的图片和类型等设置
		 */
		btnMapFull:function(){
			var btnMap = new Map();
			btnMap.put("ADD",{name:"新增",code:"ADD",imgPth:"images/icon_add.png"});
			btnMap.put("EDIT",{name:"修改",code:"EDIT",imgPth:"images/icon_edit.png"});
			btnMap.put("DEL",{name:"删除",code:"DEL",imgPth:"images/icon_del.png"});
			btnMap.put("START",{name:"启用",code:"START",imgPth:"images/icon_start.png"});
			btnMap.put("STOP",{name:"停用",code:"STOP",imgPth:"images/icon_stop.png"});
			btnMap.put("SYN",{name:"同步",code:"SYN",imgPth:"images/icon_synchronization.png"});
			btnMap.put("EXPORT",{name:"导出",code:"EXPORT",imgPth:"images/icon_export.png"});
			btnMap.put("IMPORT",{name:"导入",code:"IMPORT",imgPth:"images/icon_Import.png"});
			btnMap.put("PRINT",{name:"打印",code:"PRINT",imgPth:"images/icon_print.png"});
			return btnMap;
		},
		/**
		 * 通过imgPth获取按钮code
		 * @param imgPth
		 */
		getBtnCode:function(imgPth){
			var btnList = this.btnMaps.values();
			for(var i = 0;i < btnList.length; i ++){
				if(btnList[i]["imgPth"] == imgPth){
					return btnList[i]["code"];
				}
			}
		}
};
